<template>
  <div class="department-container">
    <a-card>
      <!-- 顶部操作区 -->
      <div class="table-operations">
        <!-- 添加搜索框 -->
        <a-row :gutter="16">
          <a-col :span="6">
            <a-input-search
                v-model:value="search"
                placeholder="请输入用户名称"
                @search="fetchUserList"
                enter-button
            />
          </a-col>
          <a-col :span="18" style="text-align: right">
            <a-button type="primary" @click="showAddModal">
              <plus-outlined />
              添加用户
            </a-button>
          </a-col>
        </a-row>
      </div>

      <!-- 部门表格 -->
      <a-table
          :columns="columns"
          :data-source="userList"
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
      >
        <!-- 操作列 -->
        <template  v-slot:bodyCell="{column,record}">

          <template v-if="column.dataIndex === 'departmentId'">
            <a-tag color="green">{{ getDepartmentName(record.departmentId) }}</a-tag>
          </template>
          <template v-if="column.dataIndex === 'phone'">
            <span class="phone-number">{{ record.phone }}</span>
          </template>
          <template v-if="column.dataIndex === 'sex'">
            <a-tag :color="record.sex === 1 ? 'blue' : 'pink'">
              {{ record.sex === 1 ? '男' : '女' }}
            </a-tag>
          </template>
          <template v-if="column.dataIndex == 'action'">
            <a-space>
              <a-button type="link" @click="showEditModal(record)">编辑</a-button>
              <a-popconfirm
                  title="确定要删除这个用户吗？"
                  @confirm="handleDelete(record.userId)"
              >
                <a-button type="link" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>

      <a-modal
          :title="modalTitle"
          :open="modalVisible"
          @ok="handleModalOk"
          @cancel="handleModalCancel"
      >
        <a-form
            ref="formRef"
            :model="formData"
            :rules="rules"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 16 }"
        >
          <a-form-item label="账号" name="username">
            <a-input v-model:value="formData.username" placeholder="请输入账号" />
          </a-form-item>
          <a-form-item label="密码" name="password">
            <a-input-password v-model:value="formData.password" placeholder="请输入密码" />
          </a-form-item>
          <a-form-item label="年龄" name="age">
            <a-input v-model:value="formData.age" placeholder="请输入年龄" />
          </a-form-item>
          <a-form-item label="手机号" name="phone">
            <a-input v-model:value="formData.phone" placeholder="请输入手机号" />
          </a-form-item>
          <a-form-item label="性别" name="sex">
            <a-select
                v-model:value="formData.sex"
                placeholder="请选择性别"
                class="custom-select"
            >
              <a-select-option :value="1">
                <man-outlined style="color: #1890ff" /> 男
              </a-select-option>
              <a-select-option :value="2">
                <woman-outlined style="color: #eb2f96" /> 女
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="部门" name="departmentId">
            <a-select
                v-model:value="formData.departmentId"
                placeholder="请选择部门"
                show-search
                :filter-option="filterDepartmentOption"
                class="custom-select"
            >
              <a-select-option
                  v-for="dept in getDepartmentList"
                  :key="dept.departmentId"
                  :value="dept.departmentId"
              >
                {{ dept.departmentName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </a-modal>
    </a-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {ManOutlined, PlusOutlined, UserOutlined, WomanOutlined} from '@ant-design/icons-vue'
import { list,add,del,update } from '@/api/user'
import { getDataList } from '@/api/data'
// 表格列定义
const columns = [
  {
    title: '账号',
    dataIndex: 'username',
    key: 'username',
  },
  {
    title: '密码',
    dataIndex: 'password',
    key: 'password',
    customRender: () => '******'
  },
  {
    title:'年龄',
    dataIndex:'age',
    key:'age'
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    key: 'phone',
  },
  {
    title: '性别',
    dataIndex: 'sex',
    key:'sex'
  },
  {
    title:'部门',
    dataIndex:'departmentId',
    key:'departmentId'
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
  },
]

// 数据相关
const loading = ref(false)
const getDepartmentList=ref([])
const userList = ref([])
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
})
const search=ref('')
// 模态框相关
const modalVisible = ref(false)
const modalTitle = ref('添加管理员')
const formRef = ref(null)
const formData = ref({
  username: '',
  password: '',
  age:'',
  sex:'',
  phone:'',
  departmentId:''
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  departmentId: [
    { required: true, message: '请选择部门', trigger: 'blur' }
  ],
  sex: [
    { required: true, message: '请选择性别', trigger: 'blur' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { pattern: /^[1-9]\d*$/, message: '年龄必须为正整数', trigger: 'blur' },
    {
      validator: (rule, value) => {
        if (value < 18) {
          return Promise.reject('年龄必须大于等于18岁');
        }
        return Promise.resolve();
      },
      trigger: 'blur',
    },
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
  ],

}
const getDepartmentName = (departmentId) => {
  const department = getDepartmentList.value.find(dept => dept.departmentId === departmentId)
  return department ? department.departmentName : '-'
}
const DataList=async()=>{
  const res =await getDataList();
  console.log(res)
  if(res.code===200){
    getDepartmentList.value=res.data.departmentInfoList
  }
}
// 获取部门列表
const fetchUserList = async () => {
  loading.value = true
  try {
    const res = await list({
      pageNum:pagination.value.current,
      pageSize:pagination.value.pageSize,
      search:search.value
    })
    console.log(res)
    userList.value = res.data.records
    pagination.value.total = res.data.total
  } catch (error) {
    message.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 表格分页变化
const handleTableChange = (pag) => {
  pagination.value.current = pag.current
  pagination.value.pageSize = pag.pageSize
  fetchUserList()
}

// 显示添加模态框
const showAddModal = () => {
  modalTitle.value = '添加用户'
  formData.value = {
    username: '',
    password: '',
    age:'',
    sex:'',
    phone:'',
    departmentId:'',
  }
  modalVisible.value = true
}

// 显示编辑模态框
const showEditModal = (record) => {
  modalTitle.value = '编辑用户'
  formData.value = { ...record }
  modalVisible.value = true
}

// 处理模态框确认
const handleModalOk = () => {
  formRef.value?.validate().then(async () => {
    try {
      const res=formData.value.userId ? await update(formData.value) : await add(formData.value)
      if(res.code===200){
        message.success(`${modalTitle.value}成功`)
        modalVisible.value = false
        fetchUserList()
      }
    } catch (error) {
      message.error(`${modalTitle.value}失败`)
    }
  })
}

// 处理模态框取消
const handleModalCancel = () => {
  modalVisible.value = false
  formRef.value?.resetFields()
}

const handleDelete = async (userId) => {
  try {

    const res=await del(userId)
    if(res.code===200){
      message.success('删除成功')
      fetchUserList()
    }

  } catch (error) {
    message.error('删除失败')
  }
}

// 搜索处理函数
const onSearch = () => {
  pagination.value.current = 1 // 重置页码到第一页
  fetchUserList()
}
const filterDepartmentOption = (input, option) => {
  return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
}

// 页面加载时获取管理员列表
onMounted(() => {
  fetchUserList()
  DataList()
})
</script>

<style scoped>
.department-container {
  padding: 24px;
}

.table-operations {
  margin-bottom: 16px;
  .ant-row {
    width: 100%;
  }
}
</style>
